package com.getpebble.android.main.sections.settings.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.framework.FrameworkEventReceiver;
import com.getpebble.android.framework.FrameworkEventReceiver.IFrameworkEventListener;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.endpoint.InstallFileEndpoint.Result;
import com.getpebble.android.framework.install.FileDownloadManager;
import com.getpebble.android.main.sections.settings.activity.LanguageSelectionActivity;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.sun.mail.smtp.SMTPMessage;

public class LanguageInstallFragment extends PblBaseFragment {
    private static final String TAG = LanguageInstallFragment.class.getSimpleName();
    private ProgressBar mDownloadSpinner;
    private PblAsyncTask mDownloadTask;
    private FileDownloadManager mFileDownloadManager;
    private PblFrameworkInterface mFrameworkInterface = null;
    private IFrameworkEventListener mInstallEventListener = new IFrameworkEventListener() {
        public void onFrameworkStateChanged(FrameworkState newState) {
            if (newState != null && newState.getLastEvent() != null) {
                Activity activity = LanguageInstallFragment.this.getActivity();
                if (activity == null) {
                    Trace.debug(LanguageInstallFragment.TAG, "Activity is null, dropping event");
                    return;
                }
                switch (AnonymousClass3.$SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[newState.getLastEvent().ordinal()]) {
                    case SMTPMessage.RETURN_FULL /*1*/:
                        LanguageInstallFragment.this.mFileDownloadManager.deleteFile(LanguageInstallFragment.this.mLocalFileUri.toString());
                        LanguageInstallFragment.this.mLocalFileUri = null;
                        Result result = Result.fromValue(newState.getFileInstallResult());
                        if (result != Result.SUCCESS) {
                            Trace.error(LanguageInstallFragment.TAG, "Error installing file: " + result.toString());
                            Toast.makeText(activity, R.string.language_selection_error_message, 1).show();
                            LanguageInstallFragment.this.exit(activity);
                            return;
                        } else if (LanguageInstallFragment.this.isResumed()) {
                            LanguageInstallFragment.this.nextFragment(activity);
                            return;
                        } else {
                            Trace.debug(LanguageInstallFragment.TAG, "Successfully finished install but fragment is not resumed; caching success");
                            LanguageInstallFragment.this.mIsComplete = true;
                            return;
                        }
                    case SMTPMessage.RETURN_HDRS /*2*/:
                        Trace.debug(LanguageInstallFragment.TAG, "Got file install progress changed");
                        if (LanguageInstallFragment.this.isResumed()) {
                            LanguageInstallFragment.this.mInstallProgress.setProgress(newState.getFileInstallProgress());
                            return;
                        }
                        return;
                    default:
                        Trace.info(LanguageInstallFragment.TAG, "Dropping event: " + newState.getLastEvent());
                        return;
                }
            }
        }
    };
    private String mInstallLanguageLocale;
    private String mInstallLanguageName;
    private String mInstallLanguageUrl;
    private int mInstallLanguageVersion;
    private ProgressBar mInstallProgress;
    private boolean mIsComplete = false;
    private boolean mIsInstalling = false;
    private boolean mIsOnboarding = false;
    private Uri mLocalFileUri;

    static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType = new int[EventType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[EventType.FILE_INSTALL_COMPLETE.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$common$model$FrameworkState$EventType[EventType.FILE_INSTALL_PROGRESS_CHANGED.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_language_installing;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.warning(TAG, "init() activity is null, not initializing");
            return;
        }
        this.mIsOnboarding = activity instanceof OnboardingActivity;
        if (!this.mIsOnboarding) {
            container.findViewById(R.id.onboarding_banner).setVisibility(8);
        }
        this.mFileDownloadManager = new FileDownloadManager(activity, "languages");
        this.mInstallProgress = (ProgressBar) container.findViewById(R.id.language_install_progress);
        this.mInstallProgress.setVisibility(8);
        this.mDownloadSpinner = (ProgressBar) container.findViewById(R.id.language_download_spinner);
        this.mFrameworkInterface = getFrameworkInterface();
        registerFrameworkStateEventListener(this.mInstallEventListener);
    }

    public void onResume() {
        boolean isDownloading = true;
        super.onResume();
        final Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "Activity is null; short-circuiting onResume");
        } else if (handleArguments()) {
            Trace.debug(TAG, String.format("Set up language install fragment; language=<%s>, url=<%s>", new Object[]{this.mInstallLanguageName, this.mInstallLanguageUrl}));
            if (this.mIsComplete) {
                Trace.debug(TAG, "Fragment resumed in isComplete state; going to next fragment");
                nextFragment(activity);
            } else if (this.mIsInstalling) {
                Trace.debug(TAG, "Language installation is in progress but not yet complete; not downloading file");
            } else {
                boolean isFileDownloaded;
                if (this.mLocalFileUri != null) {
                    isFileDownloaded = true;
                } else {
                    isFileDownloaded = false;
                }
                if (isFileDownloaded) {
                    Trace.debug(TAG, "File already downloaded but the install was not completed and is not in progress");
                    startInstall();
                    return;
                }
                if (this.mDownloadTask == null) {
                    isDownloading = false;
                }
                if (isDownloading) {
                    Trace.debug(TAG, "Currently downloading; fragment will be updated when download completes");
                    return;
                }
                this.mDownloadTask = new PblAsyncTask() {
                    public boolean doInBackground() {
                        Trace.debug(LanguageInstallFragment.TAG, "Starting file download...");
                        LanguageInstallFragment.this.mLocalFileUri = Uri.fromFile(LanguageInstallFragment.this.mFileDownloadManager.getFile(LanguageInstallFragment.this.mFileDownloadManager.downloadFile(LanguageInstallFragment.this.mInstallLanguageUrl)));
                        Trace.debug(LanguageInstallFragment.TAG, "Finished file download successfully; got URI: " + LanguageInstallFragment.this.mLocalFileUri);
                        return true;
                    }

                    public void onTaskSuccess() {
                        new Handler(activity.getMainLooper()).post(new Runnable() {
                            public void run() {
                                if (LanguageInstallFragment.this.isResumed()) {
                                    LanguageInstallFragment.this.startInstall();
                                } else {
                                    Trace.info(PblAsyncTask.TAG, "Finished downloading file but fragment is not resumed; not starting install");
                                }
                            }
                        });
                        LanguageInstallFragment.this.mDownloadTask = null;
                    }

                    public void onTaskFailed() {
                        LanguageInstallFragment.this.mDownloadTask = null;
                        Trace.error(TAG, "Failed to download language pack");
                        new Handler(activity.getMainLooper()).post(new Runnable() {
                            public void run() {
                                Toast.makeText(activity, R.string.language_selection_error_message, 1).show();
                            }
                        });
                        LanguageInstallFragment.this.exit(activity);
                    }
                };
                this.mDownloadTask.submit();
            }
        } else {
            Trace.error(TAG, "Failed to set up fragment; finishing fragment");
            exit(activity);
        }
    }

    private void startInstall() {
        Trace.debug(TAG, "startInstall()");
        this.mIsInstalling = true;
        this.mDownloadSpinner.setVisibility(8);
        this.mInstallProgress.setVisibility(0);
        PblDevice device = getConnectedDevice();
        if (device == null) {
            Trace.debug(TAG, "Device disconnected; waiting for activity to clean up the fragment");
        } else {
            this.mFrameworkInterface.installLanguage(device, this.mLocalFileUri, this.mInstallLanguageLocale, this.mInstallLanguageVersion);
        }
    }

    public void onDestroy() {
        unregisterFrameworkStateEventListener(this.mInstallEventListener);
        if (this.mDownloadTask != null) {
            this.mDownloadTask.cancel();
            this.mDownloadTask = null;
        }
        super.onDestroy();
    }

    private boolean handleArguments() {
        Bundle args = getArguments();
        if (args == null) {
            Trace.error(TAG, "Cannot install language; no arguments provided to fragment");
            return false;
        } else if (args.containsKey("extra_install_language_url")) {
            this.mInstallLanguageUrl = args.getString("extra_install_language_url");
            if (args.containsKey("extra_install_language_name")) {
                this.mInstallLanguageName = args.getString("extra_install_language_name");
                if (args.containsKey("extra_install_language_locale")) {
                    this.mInstallLanguageLocale = args.getString("extra_install_language_locale");
                    if (args.containsKey("extra_install_language_version")) {
                        this.mInstallLanguageVersion = args.getInt("extra_install_language_version");
                        return true;
                    }
                    Trace.error(TAG, "Cannot install language; no language version provided");
                    return false;
                }
                Trace.error(TAG, "Cannot install language; no locale provided");
                return false;
            }
            Trace.error(TAG, "Cannot install language; no user-facing language name provided");
            return false;
        } else {
            Trace.error(TAG, "Cannot install language; no URL provided");
            return false;
        }
    }

    void registerFrameworkStateEventListener(IFrameworkEventListener eventListener) {
        FrameworkEventReceiver.registerFrameworkStateEventListener(eventListener);
    }

    void unregisterFrameworkStateEventListener(IFrameworkEventListener eventListener) {
        FrameworkEventReceiver.unregisterFrameworkStateEventListener(eventListener);
    }

    PblFrameworkInterface getFrameworkInterface() {
        return PebbleApplication.getFrameworkInterface();
    }

    PblDevice getConnectedDevice() {
        return PebbleApplication.getConnectedDevice();
    }

    private void exit(Activity activity) {
        if (this.mIsOnboarding) {
            ((OnboardingActivity) activity).goToNextScreen();
            return;
        }
        Trace.error(TAG, "Finishing activity");
        activity.finish();
    }

    private void nextFragment(Activity activity) {
        Fragment fragment = new LanguageSelectionCompleteFragment();
        fragment.setArguments(getArguments());
        if (this.mIsOnboarding) {
            ((OnboardingActivity) activity).switchScreenFragment(fragment);
        } else if (activity instanceof LanguageSelectionActivity) {
            ((LanguageSelectionActivity) activity).switchScreenFragment(fragment);
        } else {
            Trace.error(TAG, "Finished scene but don't know where to transition; finishing activity");
            activity.finish();
        }
    }

    public boolean isInstalling() {
        return this.mIsInstalling;
    }
}
